package com.logos.ruralrevitalization.controller;

import com.google.common.base.Preconditions;
import com.logos.ruralrevitalization.entity.ProductOrder;
import com.logos.ruralrevitalization.req.ProductOrderReq;
import com.logos.ruralrevitalization.resp.ProductOrderResp;
import com.logos.ruralrevitalization.result.Result;
import com.logos.ruralrevitalization.service.AuthUserService;
import com.logos.ruralrevitalization.service.ProductOrderService;
import com.logos.ruralrevitalization.utils.RuralLoginUtil;
import com.logos.ruralrevitalization.utils.TouristLoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 农产品订单表(ProductOrder)表控制层
 *
 * @author rose
 * @since 2025-03-29 13:06:35
 */
@RestController
@RequestMapping("/productOrder")
@Slf4j
public class ProductOrderController {

    @Resource
    private ProductOrderService productOrderService;

    @Resource
    private AuthUserService authUserService;

    @Resource
    private TouristLoginUtil touristLoginUtil;

    @Resource
    private RuralLoginUtil ruralLoginUtil;


    /**
     * 下单
     */
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody ProductOrderReq productOrderReq) {
        try {
            if (log.isInfoEnabled()) {
                log.info("ProductOrderController.add.productOrderReq:{}", productOrderReq);
            }
            String id = touristLoginUtil.getId();
            if (StringUtils.isBlank(id)) {
                return Result.fail("请先登录");
            }
            productOrderReq.setCustomerId(Long.valueOf(id));
            Preconditions.checkNotNull(productOrderReq.getTotalAmount(), "订单总金额不能为空");
            Preconditions.checkNotNull(productOrderReq.getShoppingCartIds(), "购物车id不能为空");
            Boolean result = productOrderService.add(productOrderReq);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("ProductOrderController.add:{}", e.getMessage(), e);
            return Result.fail("下单失败");
        }
    }



    /**
     * 订单模块展示订单
     */
    @GetMapping("/order/list")
    public Result<List<ProductOrderResp>> orderList() {
        try {
            String id = ruralLoginUtil.getId();
            if (StringUtils.isBlank(id)) {
                return Result.fail("请先登录");
            }
            List<ProductOrderResp> result = authUserService.queryRuralOrder(Long.valueOf(id));
            return Result.ok(result);
        }catch (Exception e) {
            log.error("ProductOrderController.orderList.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

}

